package com.lagou.edu.utils;

import com.alibaba.druid.pool.DruidPooledConnection;
import com.lagou.edu.annotation.Service;

import java.sql.Connection;
import java.sql.SQLException;
@Service
public class ConnectionUtils {

    /**
     * 提供getInstance 饿汉式单例模式 获取
     */
    /*private ConnectionUtils(){};

    private static ConnectionUtils  connectionUtils = new ConnectionUtils();

    public static ConnectionUtils getInstance(){
        return connectionUtils;
    }*/
    private ThreadLocal<Connection> threadLocal =  new ThreadLocal<>(); // 存储当前线程的连接
    // 对方法进行改造  将链接绑定到一个线程中，保证与数据库交互使用一个连接对象从而可以进行事物控制
    public Connection getCurrentThreadConn() throws SQLException {
        Connection connection = threadLocal.get();
        //从当前线程中获取连接，并判断是否存在，如果不存在则从连接池中获取并存在当前线程中
        if(connection == null){
            Connection connection1 = DruidUtils.getInstance().getConnection();
            threadLocal.set(connection1);
        }
        return threadLocal.get();
    }
}
